package com.hkyl.hospital.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hkyl.hospital.entity.Check;
import com.hkyl.hospital.entity.CheckExample;
import com.hkyl.hospital.entity.Dept;
import com.hkyl.hospital.mapper.CheckMapper;
import com.hkyl.hospital.mapper.DeptMapper;
import com.hkyl.hospital.service.CheckService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;

/**
 * @author whd
 * @date 2023/07/10 15:07:09
 */
@Service
@Transactional
public class CheckServiceImpl implements CheckService {
    @Autowired
    private CheckMapper checkMapper;
    @Autowired
    private DeptMapper deptMapper;
    @Override
    public List<Check> findAll() {
        List<Check> checks = checkMapper.selectByExample(null);
        setDept(checks);
        return checks;
    }

    @Override
    public int add(Check check) {
        return checkMapper.insertSelective(check);
    }

    @Override
    public int update(Check check) {
        return checkMapper.updateByPrimaryKeySelective(check);
    }

    @Override
    public int delete(Integer id) {
        return checkMapper.deleteByPrimaryKey(id);
    }

    @Override
    public PageInfo<Check> findAllByCondition(Map<String, Object> condition) {
        CheckExample checkExample = new CheckExample();
        String checkName = (String) condition.get("checkName");
        Integer pageNum = (Integer) condition.get("pageNum");
        Integer pageSize = (Integer) condition.get("pageSize");
        if (condition.get("deptId")!= null){
            Integer deptId = (Integer) condition.get("deptId");
            checkExample.or().andDeptIdEqualTo(deptId);
        }
        if (checkName!=null)
        {
            checkExample.or().andCheckNameLike("%" + checkName + "%");
        }
        PageHelper.startPage(pageNum, pageSize);
        List<Check> checks = checkMapper.selectByExample(checkExample);
        PageInfo<Check> pageInfo = new PageInfo<>(checks);
        setDept(pageInfo.getList());
        return pageInfo;
    }

    @Override
    public List<Check> listCheck() {
        return checkMapper.selectByExample(null);
    }

    private void setDept(List<Check> checks) {
        List<Dept> depts = deptMapper.selectByExample(null);
        for (Check check : checks) {
            for (Dept dept : depts) {
                if (check.getDeptId() == dept.getDeptId()) {
                    check.setDept(dept);
                }
            }
        }
    }
}
